package com.alibaba.citrus.cr.mn.order.center.facade.function.asynctask.consumer;

import com.alibaba.citrus.cr.common.enums.ordercenter.InnerMessageEventEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.OrderCategoryEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.function.asynctask.AsyncTaskCreateService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.asynctask.OrderAsyncTaskListenerConsumerSelector;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.OrderBizCreateService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.SendMsgService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.crb2btradecenter.messagetask.model.MessageTask;
import com.epoch.app.crb2btradecenter.model.enums.MessageTaskTypeEnum;
import com.epoch.app.mnordercenter.model.dto.CommonAsyncMessageResponse;
import com.epoch.app.mnordercenter.model.dto.SalesOrderAtomBatchCreateRequest;
import com.epoch.app.mnordercenter.model.dto.SalesOrderBizBatchCreateRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomCreateResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName OrderAsyncTaskSalesOrderCreateService
 * @description: TODO
 * @date 2023/06/06 11:12
 * @version: 1.0
 */
@Component("orderAsyncTaskGroupSalesOrderCreateComponent")
public class OrderAsyncTaskGroupSalesOrderCreateComponent implements OrderAsyncTaskListenerConsumerSelector {
    private static final Log log = Log.getLogger(OrderAsyncTaskGroupSalesOrderCreateComponent.class);

    @Resource
    private SendMsgService sendMsgService;

    @Resource
    private AsyncTaskCreateService asyncTaskCreateService;

    @Resource(name = "salesOrderBizCreateService")
    private OrderBizCreateService<SalesOrderBizBatchCreateRequest, SalesOrderAtomBatchCreateRequest, OrderAtomCreateResponse> salesOrderBizCreateService;

    @Override
    public MessageTaskTypeEnum getMessageTaskType() {
        return MessageTaskTypeEnum.OC_DIRECT_SALES_ORDER_BATCH_CREATE;
    }

    @Override
    public void doConsumer(String ossTaskContent, MessageTask messageTask) {
        SalesOrderBizBatchCreateRequest createRequest = JSONObject.parseObject(ossTaskContent, SalesOrderBizBatchCreateRequest.class);
        log.info("OrderAsyncTaskGroup_doCreate_SalesOrder request={}", JSON.toJSONString(createRequest));
        String orderCategoryCode = createRequest.getOrderList().get(0).getOrderCategoryCode();

        List<OrderAtomCreateResponse> createResponses = salesOrderBizCreateService.batchCreate(createRequest);
        log.info("OrderAsyncTaskGroup_doCreate_SalesBizOrder result={}", JSON.toJSONString(createResponses));

        // 发送kafka消息通知应用端处理结果
        CommonAsyncMessageResponse commonAsyncMessageResponse = convertCommonAsyncMessageResponse(messageTask.getBatchNo(), createRequest.getFromSys(), createRequest.getBusinessUnitCode(), createResponses);
        sendMsgService.sendMsgToSendKafka(commonAsyncMessageResponse);
        log.info("OrderAsyncTaskSalesGroupOrderCreateComponent#doConsumer sendMsgToSendKafka message={}", commonAsyncMessageResponse);

        // 发送MQ消息通知其他中心
        sendMsg(createResponses, orderCategoryCode);

        // 上传原子结果
        asyncTaskCreateService.appendAsyncTaskHandleResult(JSON.toJSONString(createResponses), messageTask.getBatchNo(), messageTask);
    }

    @Override
    public void sendOccupyInventoryOccupyMsg(List<String> bizOrderId) {
    }

    private void sendMsg(List<OrderAtomCreateResponse> createResponses, String orderCategoryCode) {
        // 过滤创建失败的单据
        List<OrderAtomCreateResponse> successCreateResponses = Optional.ofNullable(createResponses).orElse(Lists.newArrayList())
                .stream()
                .filter(p -> StringUtils.isBlank(p.getErrorCode()))
                .collect(Collectors.toList());

        List<String> salesOrderNos = successCreateResponses.stream()
                .map(OrderAtomCreateResponse::getSalesOrderNo)
                .filter(StringUtils::isNotBlank)
                .distinct().collect(Collectors.toList());

        if (CollectionUtils.isEmpty(salesOrderNos)) {
            log.info("sendMsgToInventoryOccupy_DATA_EMPTY_SKIP result={}", JSONArray.toJSONString(createResponses));
            return;
        }

        if (!OrderCategoryEnum.GROUP.getCode().equals(orderCategoryCode)) {
            // 非集团订单发消息预占库存，集团订单通过履约中心进行预占
            sendOccupyInventoryOccupyMsg(salesOrderNos);
        }

        // 发送MQ消息通知其他中心
        sendMsgService.sendSalesOrderChangeMsg(salesOrderNos, InnerMessageEventEnum.SALES_ORDER_CREATED);
    }
}
